package com.example.demo.controller;

import com.example.demo.entity.ResultEntity;
import com.example.demo.service.serviceimpl.CartServiceImpl;
import com.example.demo.vo.CartVo;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

@RequestMapping("v2/cart/")
@CrossOrigin
@RestController
public class CartController {
    @Resource
    CartServiceImpl cartService;
    
    // 获取用户购物车
    @GetMapping("getUserCart")
    private ResultEntity getUserCart(@RequestParam("user_id") Integer user_id) {
        ResultEntity resultEntity = new ResultEntity();
        try {
            resultEntity.setCode(0);
            resultEntity.setMsg("获取成功");
            resultEntity.setData(cartService.getUserCart(user_id));
        } catch (Exception e) {
            resultEntity.setCode(-1);
            resultEntity.setMsg("商品获取失败");
            e.printStackTrace();
        }
        return resultEntity;
    }
    // 更新购物车
    @PutMapping("updateCart")
    private ResultEntity updateCart(@RequestBody CartVo cartVo) {
        ResultEntity resultEntity = new ResultEntity();
        try{
            if(cartService.updateCart(cartVo)>0){
                resultEntity.setCode(0);
                resultEntity.setMsg("修改成功");
            }else{
                resultEntity.setCode(-1);
                resultEntity.setMsg("修改失败");
            }


        }catch (Exception e){
            resultEntity.setCode(-1);
            resultEntity.setMsg("错误");
            e.printStackTrace();
        }
        return resultEntity;
    }
    // 添加到购物车
    @PostMapping("addCart")
    private ResultEntity addCart(@RequestBody CartVo cartVo) {
        ResultEntity resultEntity = new ResultEntity();
        try{
            if(cartService.addCart(cartVo)>0){
                resultEntity.setCode(0);
                resultEntity.setMsg("添加成功");
            }else{
                resultEntity.setCode(-1);
                resultEntity.setMsg("添加失败");
            }
        } catch (Exception e) {
            resultEntity.setCode(-1);
            resultEntity.setMsg("错误");
            e.printStackTrace();
        }
        return resultEntity;
    }
    // 删除购物车项
    @DeleteMapping("deleteCart")
    private ResultEntity deleteCart(@RequestParam("id") Integer id) {
        ResultEntity resultEntity = new ResultEntity();
        try{
            if(cartService.deleteCart(id)>0){
                resultEntity.setCode(0);
                resultEntity.setMsg("删除成功");
            }else{
                resultEntity.setCode(-1);
                resultEntity.setMsg("删除失败");
            }
        }catch (Exception e) {
            resultEntity.setCode(-1);
            resultEntity.setMsg("错误");
            e.printStackTrace();
        }
        return resultEntity;
    }

}
